package com.hogan.basiclibrary.base.baseApi.rx;



import com.hogan.basiclibrary.base.baseApi.exception.ServerApiException;
import com.hogan.basiclibrary.base.baseApi.protocol.BaseProtocol;
import com.hogan.basiclibrary.base.baseApi.protocol.ConcreteProtocol;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by chenhu on 2017/8/15.
 */

public class SchedulersCompat {


    public static <T> Observable.Transformer<T, T> applyIoSchedulers() {
        return (Observable.Transformer<T, T>) transformer;
    }


    private static Observable.Transformer transformer = new Observable.Transformer() {
        @Override
        public Object call(final Object observable) {
            return ((Observable) observable).map(new Func1<BaseProtocol, ConcreteProtocol>() {
                @Override
                public ConcreteProtocol call(BaseProtocol baseProtocol) {
                    return new ConcreteProtocol(baseProtocol);
                }
            }).flatMap(new Func1<ConcreteProtocol, Object>() {
                @Override
                public Object call(ConcreteProtocol concreteProtocol) {
                    Object object = concreteProtocol.parsed();
                    if (object instanceof ServerApiException) {
                        return Observable.error((ServerApiException) object);
                    } else {
                        return Observable.just(object);
                    }
                }
            }).subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    };
}
